from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection

from rest_framework.views import APIView

from rest_framework.response import Response
from order import models
from user.models import UserInfo
from order import serializer


class ShoppingCarAPIView(APIView):
    message = {}
    
    # 初始化函数
    def __init__(self):
        self.connect = get_redis_connection('default')
    
    def get(self, request, *args, **kwargs):
        user_name = kwargs.get('name')
        key = f'cart_{user_name}'
        tmp = self.connect.hgetall(key)
        if not tmp:
            message = {
                'status': 101,
                "message": "购物车为空！"
            }
            return Response(data=message)
        # 字典生成器获取 商品id：数量
        data = {k.decode('utf-8'): v.decode('utf-8') for k, v in tmp.items()}
        print(data)
        # 筛选商品
        goods = models.Goods.objects.filter(id__in=data).all()
        data_list = []
        for good in goods:
            good_info = {'good_id': good.pk, 'good_title': good.title, 'store': good.store.name,
                         'price': good.sale_price}
            data_list.append(good_info)
        message = {
            'status': 200,
            "message": "",
            'data': data_list
        }
        return Response(data=message)
    
    def put(self, request, *args, **kwargs):
        data = request.data
        user_name = data.get('user_name')
        good_id = data.get('good_id')
        count = data.get('count', 0)
        key = 'cart_' + str(user_name)
        print(key, good_id, count)
        # 存入redis
        
        self.connect.hset(key, good_id, count)
        return Response({
            "msg": "添加成功！"
        })

    def delete(self, request, *args, **kwargs):
        data = request.data
        user_name = data.get('user_name')
        good_id = data.get('good_id')
        # 存入redis
        key = 'cart_' + str(user_name)
        tmp = self.connect.hdel(key, good_id)
        print(tmp)
        return Response({
            "msg": "删除成功！"
        })